﻿using log4net;
using Newtonsoft.Json;
using RS.BaseModel.Common;

namespace TPWorkPlat.Server.Middleware
{
    public class ExceptionHandlerMiddleWare
    {
        private readonly RequestDelegate next;

        private static ILog logger = log4net.LogManager.GetLogger("ExceptionHandlerMiddleWare");

        public ExceptionHandlerMiddleWare(RequestDelegate next)
        {
            this.next = next;
        }

        public async Task Invoke(HttpContext context)
        {
            try
            {
                await next(context);
            }
            catch (Exception ex)
            {
                await HandleExceptionAsync(context, ex);
            }
        }

        private static async Task HandleExceptionAsync(HttpContext context, Exception exception)
        {
            if (exception == null)
            {
                return;
            }

            await WriteExceptionAsync(context, exception).ConfigureAwait(false);
        }

        private static async Task WriteExceptionAsync(HttpContext context, Exception exception)
        {
            var ip = context.Request.Headers["X-Forwarded-For"].FirstOrDefault();
            if (string.IsNullOrEmpty(ip))
            {
                ip = context.Connection.RemoteIpAddress == null ? "" : context.Connection.RemoteIpAddress.ToString();
            }
            logger.Error(JsonConvert.SerializeObject(exception));
            //返回友好的提示
            HttpResponse response = context.Response;
            response.ContentType = "text/html;charset=UTF-8";

            CommonResult result = new CommonResult()
            {
                IsError = true,
                Message = exception.ToString(),
                Value = RS.BaseModel.Enum.EnumBaseResult.SystemError
            };

            await response.WriteAsJsonAsync(result).ConfigureAwait(false);
        }
    }
}
